package com.yarolegovich.sample;

import com.yarolegovich.lovelydialog.LovelyChoiceDialog;
import com.yarolegovich.lovelydialog.LovelyDialogCompat;
import com.yarolegovich.lovelydialog.LovelyInfoDialog;
import com.yarolegovich.lovelydialog.LovelyProgressDialog;
import com.yarolegovich.lovelydialog.LovelySaveStateHandler;
import com.yarolegovich.lovelydialog.LovelyStandardDialog;
import com.yarolegovich.lovelydialog.LovelyTextInputDialog;
import com.yarolegovich.lovelydialog.ResUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.PacMap;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends Ability implements Component.ClickedListener {
    // This can be any numbers. ResourceTable.Id_* were chosen for simplicity of example
    private static final int ID_STANDARD_DIALOG = ResourceTable.Id_btn_standard_dialog;
    private static final int ID_SINGLE_CHOICE_DIALOG = ResourceTable.Id_btn_single_choice_dialog;
    private static final int ID_INFO_DIALOG = ResourceTable.Id_btn_info_dialog;
    private static final int ID_MULTI_CHOICE_DIALOG = ResourceTable.Id_btn_multi_choice_dialog;
    private static final int ID_TEXT_INPUT_DIALOG = ResourceTable.Id_btn_text_input_dialog;
    private static final int ID_PROGRESS_DIALOG = ResourceTable.Id_btn_progress_dialog;
    /*
     * This guy should be shared by multiple dialogs. You need to pass this object
     * to setInstanceStateHandler of dialog together with unique ID (it will be used to determine
     * what dialog was shown before configuration change if any.
     */
    private LovelySaveStateHandler saveStateHandler;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_activity_main);
        saveStateHandler = new LovelySaveStateHandler();
        findComponentById(ResourceTable.Id_btn_standard_dialog).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_single_choice_dialog).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_info_dialog).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_multi_choice_dialog).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_text_input_dialog).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_progress_dialog).setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        // View's ID correspond to our constants, so we just pass it
        showLovelyDialog(component.getId(), null);
    }

    private void showLovelyDialog(int dialogId, PacMap savedInstanceState) {
        switch (dialogId) {
            case ID_STANDARD_DIALOG:
                showStandardDialog(savedInstanceState);
                break;
            case ID_TEXT_INPUT_DIALOG:
                showTextInputDialog(savedInstanceState);
                break;
            case ID_SINGLE_CHOICE_DIALOG:
                showSingleChoiceDialog(savedInstanceState);
                break;
            case ID_MULTI_CHOICE_DIALOG:
                showMultiChoiceDialog(savedInstanceState);
                break;
            case ID_INFO_DIALOG:
                showInfoDialog(savedInstanceState);
                break;
            case ID_PROGRESS_DIALOG:
                showProgressDialog(savedInstanceState);
                break;
            default:
                break;
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        saveStateHandler.saveInstanceState(outState);
        super.onSaveAbilityState(outState);
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        if (LovelySaveStateHandler.wasDialogOnScreen(inState)) {
            // Dialog won't be restarted automatically, so we need to call this method.
            // Each dialog knows how to restore its state
            showLovelyDialog(LovelySaveStateHandler.getSavedDialogId(inState), inState);
        }
    }

    private void showStandardDialog(PacMap savedInstanceState) {
        new LovelyStandardDialog(this, LovelyStandardDialog.ButtonLayout.VERTICAL)
                .setTopColorRes(ResourceTable.Color_indigo)
                .setButtonsColorRes(ResourceTable.Color_darkDeepOrange)
                .setIcon(ResourceTable.Media_ic_star_border_white_36dp)
                .setTitle(ResourceTable.String_rate_title)
                .setInstanceStateHandler(ID_STANDARD_DIALOG, saveStateHandler)
                .setSavedInstanceState(savedInstanceState)
                .setMessage(ResourceTable.String_rate_message)
                .setPositiveButton(ResourceTable.String_ok, LovelyDialogCompat.wrap(
                        (dialog, which) ->
                                new ToastDialog(getContext()).setContentCustomComponent(showToast(ResUtil.getString(getContext(), ResourceTable.String_repo_waiting))).show()))
                .setNeutralButton(ResourceTable.String_later, null)
                .setNegativeButton(ResourceTable.String_no, null)
                .show();

    }

    private void showSingleChoiceDialog(PacMap savedInstanceState) {
        List<DonationOption> list = loadDonationOptions();
        DonationAdapter adapter = new DonationAdapter(this, loadDonationOptions());
        new LovelyChoiceDialog(this)
                .setTopColorRes(ResourceTable.Color_darkGreen)
                .setTitle(ResourceTable.String_donate_title)
                .setInstanceStateHandler(ID_SINGLE_CHOICE_DIALOG, saveStateHandler)
                .setIcon(ResourceTable.Media_ic_local_atm_white_36dp)
                .setMessage(ResourceTable.String_donate_message)
                .setItems(adapter, (position, item) ->
                        new ToastDialog(getContext()).setContentCustomComponent(showToast(String.format(getString(ResourceTable.String_you_donated), list.get(position).amount))).show()
                )
                .setSavedInstanceState(savedInstanceState)
                .show();
    }

    private void showInfoDialog(PacMap savedInstanceState) {
        new LovelyInfoDialog(this)
                .setTopColorRes(ResourceTable.Color_darkBlueGrey)
                .setIcon(ResourceTable.Media_ic_info_outline_white_36dp)
                .setInstanceStateHandler(ID_INFO_DIALOG, saveStateHandler)
                .setNotShowAgainOptionEnabled(0)
                .setNotShowAgainOptionChecked(true)
                .setSavedInstanceState(savedInstanceState)
                .setTitle(ResourceTable.String_info_title)
                .setMessage(ResourceTable.String_info_message)
                .show();
    }

    /*
     * By passing theme as a second argument to constructor - we can tint checkboxes/edittexts.
     * Don't forget to set your theme's parent to Theme.AppCompat.Light.Dialog.Alert
     */
    private void showMultiChoiceDialog(PacMap savedInstanceState) {
        String[] items = new String[]{"Pizza", "Noodles", "Hamburger", "Pasta"};
        new LovelyChoiceDialog(this, ResourceTable.Pattern_base)
                .setTopColorRes(ResourceTable.Color_darkRed)
                .setTitle(ResourceTable.String_order_food_title)
                .setIcon(ResourceTable.Media_ic_food_white_36dp)
                .setInstanceStateHandler(ID_MULTI_CHOICE_DIALOG, saveStateHandler)
                .setItemsMultiChoice(items, (positions, items1) ->
                        new ToastDialog(getContext()).setContentCustomComponent(showToast(String.format(getString(ResourceTable.String_you_ordered), join("\n", items1)))).show()

                )
                .setSavedInstanceState(savedInstanceState)
                .show();
    }

    public String getString(int resId) {
        return ResUtil.getString(this, resId);
    }

    public String join(CharSequence delimiter, Iterable tokens) {
        final Iterator<?> it = tokens.iterator();
        if (!it.hasNext()) {
            return "";
        }
        final StringBuilder sb = new StringBuilder();
        sb.append(it.next());
        while (it.hasNext()) {
            sb.append(delimiter);
            sb.append(it.next());
        }
        return sb.toString();
    }

    private void showTextInputDialog(PacMap savedInstanceState) {
        new LovelyTextInputDialog(this)
                .setTopColorRes(ResourceTable.Color_darkDeepOrange)
                .setTitle(ResourceTable.String_text_input_title)
                .setMessage(ResourceTable.String_text_input_message)
                .setIcon(ResourceTable.Media_ic_assignment_white_36dp)
                .setInstanceStateHandler(ID_TEXT_INPUT_DIALOG, saveStateHandler)
                .setInputFilter(ResourceTable.String_text_input_error_message, new LovelyTextInputDialog.TextFilter() {
                    @Override
                    public boolean check(String text) {
                        return text.matches("\\w+");
                    }
                })
                .setConfirmButton(ResourceTable.String_ok, text ->
                        new ToastDialog(getContext()).setContentCustomComponent(showToast(text)).show())
                .setNegativeButton(ResourceTable.String_no, null)
                .setSavedInstanceState(savedInstanceState)
                .configureEditText(editText -> editText.setMaxTextLines(1))
                .show();
    }

    private void showProgressDialog(PacMap savedInstanceState) {
        new LovelyProgressDialog(this)
                .setTopColorRes(ResourceTable.Color_teal)
                .setIcon(ResourceTable.Media_ic_cast_connected_white_36dp)
                .setTitle(ResourceTable.String_connecting_to_server)
                .setInstanceStateHandler(ID_PROGRESS_DIALOG, saveStateHandler)
                .setSavedInstanceState(savedInstanceState)
                .setCancelable(true)
                .show();
    }

    private List<DonationOption> loadDonationOptions() {
        List<DonationOption> result = new ArrayList<>();
        String[] raw = new String[]{"Greedy option%1$", "Rich option%100$"};
        for (String op : raw) {
            String[] info = op.split("%");
            result.add(new DonationOption(info[1], info[0]));
        }
        return result;
    }

    private DependentLayout showToast(String txt) {
        DependentLayout myLayout = new DependentLayout(this);
        // 设置布局大小
        myLayout.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
        myLayout.setHeight(DependentLayout.LayoutConfig.MATCH_CONTENT);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(200, 200, 200));
        myLayout.setBackground(element);

        // 创建一个文本
        Text text = new Text(this);
        text.setText(txt);
        text.setWidth(DependentLayout.LayoutConfig.MATCH_PARENT);
        text.setTextSize(50);
        text.setMultipleLine(true);
        text.setTextColor(Color.WHITE);
        // 设置文本的布局
        DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_CONTENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
        textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
        text.setLayoutConfig(textConfig);
        myLayout.addComponent(text);
        return myLayout;
    }
}
